import { Form, Input, Modal, TreeSelect } from 'antd'
import PropTypes from 'prop-types'
import { findOneCategory, createCategory, updateCategory } from '@/api/category'
import { useEffect } from 'react'

const CategoryForm = (props) => {
  const [form] = Form.useForm()

  useEffect(() => {
    async function fetchData () {
      if (props.category_id) {
        const { data } = await findOneCategory({
          id: props.category_id
        })

        form.setFieldsValue(data)
      }
    }
    fetchData()
  }, [props.category_id])

  const onOk = async () => {
    const values = await form.validateFields()
    if (props.category_id) {
      //更新
      await updateCategory({
        id: props.category_id,
        ...values
      })
    } else {
      //新增
      await createCategory(values)
    }
    props.onOk()
  }

  const isDetail = Boolean(props.title.includes('详情'))
  return (
    <Modal
      title={props.title}
      open={props.visible}
      maskClosable={false}
      footer={isDetail ? null : undefined}
      cancelText="取消"
      okText="确定"
      onCancel={props.onCancel}
      onOk={onOk}
    >
      <Form
        form={form}
        autoComplete="off"
        disabled={isDetail}
        labelCol={{ span: 4 }}
      >
        <Form.Item
          name="name"
          label="分类名称"
          rules={[
            {
              required: true,
              message: '分类名称'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="code"
          label="分类编码"
          rules={[
            {
              required: true,
              message: '分类编码'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="level" label="分类级别">
          <Input />
        </Form.Item>
        <Form.Item name="parent_id" label="父级分类">
          <TreeSelect
            showSearch
            allowClear
            treeNodeFilterProp='name'
            fieldNames={{
              label: 'name',
              value: 'category_id',
              children: 'children'
            }}
            treeData={props.treeData}
          />
        </Form.Item>
        <Form.Item name="description" label="描述">
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  )
}

CategoryForm.propTypes = {
  category_id: PropTypes.number,
  title: PropTypes.string.isRequired,
  treeData: PropTypes.array.isRequired,
  visible: PropTypes.bool.isRequired,
  onCancel: PropTypes.func.isRequired,
  onOk: PropTypes.func.isRequired
}

export default CategoryForm